package com.schoolMall.controller.local;

import com.schoolMall.domain.LocalAuth;
import com.schoolMall.domain.User;
import com.schoolMall.dto.LocalAuthDto;
import com.schoolMall.enums.LocalAuthStateEnum;
import com.schoolMall.exception.LocalAuthOperationException;
import com.schoolMall.service.LocalAuthService;
import com.schoolMall.utils.CodeUtil;
import com.schoolMall.utils.HttpServletRequestUtil;
import com.schoolMall.utils.ModelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author:zyh
 * @Time:2021-09-04-15:37
 * @email:1269231889@qq.com
 */
@Controller
@RequestMapping("/schoolMall/localAuth")
public class LocalAuthController {
    @Autowired
    private LocalAuthService localAuthService;
    private Logger logger = LoggerFactory.getLogger(LocalAuthController.class);

    @ResponseBody
    @PostMapping("/bindLocal")
    public Map<String, Object> bingLocalAuth(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        if (CollectionUtils.isEmpty(model = verifyCode(request))) {
            return model;
        }
        String username = HttpServletRequestUtil.getString(request, "username");
        String password = HttpServletRequestUtil.getString(request, "password");
        User user = (User) request.getSession().getAttribute("user");
        LocalAuth localAuth = new LocalAuth();
        localAuth.setUsername(username);
        localAuth.setUser(user);
        localAuth.setPassword(password);
        try {
            LocalAuthDto localAuthDto = localAuthService.bindLocalAuth(localAuth);
            if (localAuthDto.getLocalAuthStateEnum() == LocalAuthStateEnum.ONLY_ONE_USER) {
                return ModelUtil.fail(LocalAuthStateEnum.ONLY_ONE_USER.getMsg());
            } else if (localAuthDto.getLocalAuthStateEnum() == LocalAuthStateEnum.NULL_USER) {
                return ModelUtil.fail(LocalAuthStateEnum.NULL_USER.getMsg());
            }
            return ModelUtil.success(localAuthDto);
        } catch (LocalAuthOperationException e) {
            return ModelUtil.fail(e.getMessage());
        }
    }

    @ResponseBody
    @GetMapping("/modifyPassword")
    public Map<String, Object> modifyPassword(HttpServletRequest request) {
        Map<String, Object> model = null;
        if (CollectionUtils.isEmpty(model = verifyCode(request))) {
            return model;
        }
        String username = HttpServletRequestUtil.getString(request, "username");
        String password = HttpServletRequestUtil.getString(request, "password");
        String newPassword = HttpServletRequestUtil.getString(request, "newPassword");
        User user = (User) request.getSession().getAttribute("user");
        if (username != null && password != null && newPassword != null && Objects.nonNull(user) && !password.equals(newPassword)) {
            LocalAuth tempUser = localAuthService.getLocalAuthByUserId(user.getUserId());
            if (Objects.isNull(tempUser) || !username.equals(tempUser.getUsername())) {
                return ModelUtil.fail("非本次登录用户");
            }
            try {
                LocalAuthDto localAuthDto = localAuthService.modifyLocalAuth(user.getUserId(), username, password, newPassword);
                if (localAuthDto.getLocalAuthStateEnum() == LocalAuthStateEnum.NULL_USER) {
                    return ModelUtil.fail(LocalAuthStateEnum.NULL_USER.getMsg());
                }
                model.put("success", true);
                model.put("msg", localAuthDto);

            } catch (LocalAuthOperationException e) {
                return ModelUtil.fail(e.getMessage());
            }
        }
        return model;
    }

    @ResponseBody
    @PostMapping("/login")
    public Map<String, Object> login(HttpServletRequest request) {
        Map<String, Object> model = new HashMap<>();
        if (CollectionUtils.isEmpty((model = verifyCode(request)))) {
            return model;
        }
        String username = HttpServletRequestUtil.getString(request, "username");
        String password = HttpServletRequestUtil.getString(request, "password");
        if (Objects.isNull(username)||Objects.isNull(password)){
            return ModelUtil.fail("用户登录信息为空");
        }
        LocalAuth localAuth = localAuthService.getLocalAuthByUsernameAndPwd(username, password);
        if (Objects.isNull(localAuth)){
            return ModelUtil.fail("null user");
        }
        request.getSession().setAttribute("user",localAuth);
        return ModelUtil.success("login success");
    }

    @ResponseBody
    @PostMapping("/logout")
    public Map<String,Object> logout(HttpServletRequest request){
        Map<String,Object> model = new HashMap<>();
        request.getSession().setAttribute("user",null);
        model.put("success",true);
        return model;
    }

    private Map<String, Object> verifyCode(HttpServletRequest request) {
        HashMap<String, Object> model = new HashMap<>();
        if (!CodeUtil.checkVerifyCode(request)) {
            logger.info("code error");
            model.put("success", false);
            model.put("msg", "验证码错误");
            return model;
        }
        return model;
    }
}
